package com.chainyoung.common.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Looper;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.TextView;

import com.chainyoung.common.R;
import com.chainyoung.common.utils.StringUtil;


/**
 * Created by AnyOne on 2018/3/7.
 */

public class ProcessDialog {
    private BaseDialog mDialog;
    private Context mContext;
    private ImageView mImageView;
    private AnimationDrawable mDrawable;
    private TextView mLoadingText;


    public ProcessDialog(Context context) {
        mContext = context;
        if (null != mDialog && mDialog.isShowing()) {
            mDialog.close();
        }
        try {
            if (Looper.myLooper()==null) {
                Looper.prepare();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        init();
    }

    public void setLoadingText(String text) {
        if (!StringUtil.isEmpty(text)) {
            mLoadingText.setText(text);

        }
    }

    private void init() {
        BaseDialog.Builder mBuilder = new BaseDialog.Builder(mContext);
        mDialog = mBuilder.setViewId(R.layout.item_progress_dialog)
                .setGravity(Gravity.CENTER)
                .isOnTouchCanceled(false)
                .builder();
        mImageView = mDialog.getView(R.id.iv_progress);
        mLoadingText = mDialog.getView(R.id.tv_progress);

    }

    public void show() {
        mDrawable = (AnimationDrawable) mImageView.getDrawable();
        if (mDrawable != null && !mDrawable.isRunning()) {
            mDrawable.start();
        }
        Activity mActivity = (Activity) mContext;

        if (!mActivity.isFinishing()) {
            mDialog.show();
        } else {
            mDialog.close();
        }
    }

    public void close() {

        if (mDialog.isShowing() && mDialog != null) {
            if (mDrawable != null && !mDrawable.isRunning()) {
                mDrawable.stop();
            }
            mDialog.close();
        }
    }

    public boolean isShowing() {
        return mDialog.isShowing();
    }

}
